package com.example.fw;


import java.util.HashSet;
import java.util.List;
import java.util.Set;
	
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.example.tests.GroupObject;

public class GroupHelper extends HelperWithWebDriverBase {
	
	public GroupHelper (ApplicationManager manager){
			super(manager);
		}
	
	public Set<GroupObject> getGroups() {
		manager.getNavigationHelper().gotoGroupListPage();
		WebElement form = findElements(By.tagName("form")).get(1);
		List<WebElement> checkboxes = form.findElements(By.name ("selected[]"));
		Set<GroupObject> groups = new HashSet<GroupObject>(); 
		for (WebElement checkbox : checkboxes) {
			String title = checkbox.getAttribute("title");
//			
			title = title.substring("Select (".length(), title.length()-"".length());
//			
			GroupObject group =  new GroupObject().setName1(title).setId(checkbox.getAttribute("value"));
			groups.add(group);
		}
		return groups; 
	}
			
	public void creationGroup(GroupObject groupObject) {
		manager.getNavigationHelper().gotoGroupListPage();
		initGroupCration();
		fillGroupForm(groupObject);
		submitGroupCreation();
		returnToGroupListPage(); 
	}
	
	public void deleteGroup(int i) {
		manager.getNavigationHelper().gotoGroupListPage();
		checkGroup(i);
		click(By.name("delete"));
		returnToGroupListPage();

	}

	public void modifyGroup(int i, GroupObject groupObject) {
		manager.getNavigationHelper().gotoGroupListPage();
		initGroupModification(i);
		fillGroupForm(groupObject);
		submitGroupModification();
		returnToGroupListPage(); 

	}

	protected void initGroupCration() {
		click(By.name("new"));
	}
	
	private void submitGroupModification() {
		click(By.name("update"));
	}
	
	private void initGroupModification(int i) {
		checkGroup(i);
		click(By.name("edit"));
		
	}
	
	private void checkGroup(int i) {
		click(By.name("selected[]"));
	}
	
		
	protected void fillGroupForm(GroupObject groupObjectParametrName) {
		type(groupObjectParametrName.name1,"group_name");
		type(groupObjectParametrName.header,"group_header");
		type(groupObjectParametrName.footer,"group_footer");
	}
	
	protected void submitGroupCreation() {
		click(By.name("submit"));
	}
	
	protected void returnToGroupListPage() {
		click(By.linkText("group page"));
	}}
